package com.sduept.nwld.dataserver.controller.base.secondary;

import com.sduept.bigdata.web.jsf.controller.AbstractController;
import com.sduept.cim.model.core.Substation;
import com.sduept.cim.model.protection.ProtectionEquipment;
import com.sduept.core.dao.SuperDAO;
import com.sduept.core.entity.IdentifiedObject;
import com.sduept.bigdata.weather.map.MapDataCache;
import com.sduept.nwld.dataserver.manager.cim.CimManager;
import com.sduept.utils.PingYinUtil;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;

import org.primefaces.event.SelectEvent;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.PostConstruct;
import javax.inject.Named;
import javax.faces.view.ViewScoped;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Named
@ViewScoped
public class UnbindProtectDialogController extends AbstractController {
	/**
	 * 
	 */
	private static final long serialVersionUID = 4979619843390315178L;
	
	@Autowired
	private CimManager cm;
	@Autowired
	private SuperDAO dao;
	@Autowired
	private MapDataCache cc;
	/**
	 * 选择的列
	 */
	private List<ProtectionEquipmentDTO> selects = new ArrayList<ProtectionEquipmentDTO>();
	/**
	 * 对话框数据源
	 */
	private List<ProtectionEquipmentDTO> currentDeviceProList = new ArrayList<ProtectionEquipmentDTO>();// 弹出框数据源
	/**
	 * 选择的变电站
	 */
	private String station;
	/**
	 * 选择的名字
	 */
	private String deviceName;
	private String deviceId;
	private ProtectionEquipmentDTO selected = null;// 关联一次设备时选择的行
	private List<String> proKinds = new ArrayList<String>();
	// 变电站
	private List<Substation> substations = new ArrayList<>();
	public Map<String, List<String>> cimstation = new HashMap<>();
	public Map<String, List<String>> primEquipments = new HashMap<>();// 一次设备
	// 生产厂家
	public List<String> devManufacturers = new ArrayList<>();
	public Map<String, List<String>> devManufacturerMap = new HashMap<>();
	private List<String> protectedTypes = new ArrayList<>();// 一次设备类型

	@PostConstruct
	public void init() {
		String privateStationId = getParameter("privateStationId");
		String privateStationName = getParameter("privateStationName");
		privateStationName = unicodeToCn(privateStationName);
		initData(privateStationId, privateStationName);
		proKinds.clear();
		initProKind();

		// 初始化变电站
		substations = cc.getS500List();
		for (Substation r : substations) {
			String key = PingYinUtil.getPingYinHeader(r.getName());
			List<String> ss = cimstation.get(key);
			if (ss == null) {
				ss = new ArrayList<>();
				cimstation.put(key, ss);
			}
			ss.add(r.getName());
		}

		// 初始化一次设备类型
		List<?> AllProtectedTypes = dao.nativeQuery("select protected_type from t_cim_protection_equipment where protected_type is not null and protected_type !=''  group by protected_type");
		for (Object o : AllProtectedTypes) {
			protectedTypes.add(o.toString());
		}
	}

	// unicode转中文
	private static String unicodeToCn(String unicode) {
		/** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
		String[] strs = unicode.split("\\\\u");
		StringBuilder returnStr = new StringBuilder();
		// 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
		for (int i = 1; i < strs.length; i++) {
			returnStr.append((char) Integer.valueOf(strs[i], 16).intValue());
		}
		return returnStr.toString();
	}

	/**
	 * 绑定变电站，一次设备信息
	 */
	public void saveBindInfo() {
		for (ProtectionEquipmentDTO dto : selects) {
			ProtectionEquipment pe = new ProtectionEquipment();
			try {
				BeanUtils.copyProperties(pe, dto);
				String selectStation = null;
				if (StringUtils.isNotEmpty(station)) {
					for (Substation s : cc.getStationid_map().values()) {
						if (s.getName().equals(station)) {
							selectStation = s.getId();
							break;
						}
					}
				}
				int oldIndex = currentDeviceProList.indexOf(dto);// 找到原位置
				pe.setSubId(selectStation);
				pe.setSubName(station);
				pe.setProtectedId(deviceId);
				pe.setProtectedName(deviceName);
				BeanUtils.copyProperties(dto, pe);
				currentDeviceProList.set(oldIndex, dto);// 替换
				dao.createOrUpdate(pe, ProtectionEquipment.class);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
				addSuccessMessage("绑定失败");
				return;
			}
		}
		addSuccessMessage("绑定成功");
	}

	public void getEquipmentByStation() {
		String selectStation = null;
		if (StringUtils.isNotEmpty(station)) {
			for (Substation s : cc.getStationid_map().values()) {
				if (s.getName().equals(station)) {
					selectStation = s.getId();
					break;
				}
			}
		}
		Map<String, Object> options = new HashMap<String, Object>();
		options.put("resizable", true);
		options.put("draggable", true);
		options.put("modal", false);
		options.put("width", 600);
		options.put("height", 400);
		Map<String, List<String>> params = new HashMap<>();
		List<String> s = new ArrayList<>();
		s.add(selectStation);
		params.put("stationId", s);
		openDialog("/ui/common/equipment_selector_single",  params,options);
	}

	/**
	 * 设备选择对话框回调事件
	 * @param event
	 */
	public void onEquDialogChosenListener(SelectEvent event) {
		IdentifiedObject equipment = (IdentifiedObject) event.getObject();
		if (equipment != null && equipment instanceof ProtectionEquipment) {
			ProtectionEquipment pe = (ProtectionEquipment) equipment;
			deviceName = pe.getName();
			deviceId = pe.getId();
			for (ProtectionEquipmentDTO dto : selects) {
				dto.setProtectedId(pe.getId());
				dto.setProtectedName(pe.getName());
				String protectedType = cm.getEquipmentType(pe);
				dto.setProtectedType(protectedType);
				dto.setSubstationId(pe.getSubId());
				dto.setSubstationName(pe.getSubName());
				dto.setStandvoltage((int) pe.getStandVoltagelevel());
			}
			addSuccessMessage("保存成功");
		} else {
			addErrorMessage("选择必须为一次设备！");
		}
	}

	private void initData(String privateStationId, String privateStationName) {
		List<ProtectionEquipment> list = dao.findByCondition(ProtectionEquipment.class, "privateStationId=?", privateStationId);
		for (ProtectionEquipment pe : list) {
			ProtectionEquipmentDTO dto = new ProtectionEquipmentDTO();
			try {
				BeanUtils.copyProperties(dto, pe);
				dto.setPrivateStationName(privateStationName);
				currentDeviceProList.add(dto);
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
		}
	}

	public List<ProtectionEquipmentDTO> getCurrentDeviceProList() {
		return currentDeviceProList;
	}

	public void setCurrentDeviceProList(List<ProtectionEquipmentDTO> currentDeviceProList) {
		this.currentDeviceProList = currentDeviceProList;
	}

	/**
	 * 更新前台的变电站
	 */
	public void updateStationName() {

		if (selects.size() > 0) {

			station = selects.get(0).getSubstationName();
		}
	}

	/**
	 * 校验前台数据选择的条数
	 */
	public void checkSelected() {

		if (selects.size() > 0) {

			selected = selects.get(0);
			station = selects.get(0).getSubstationName();// 给变电站赋值
		} else {
			addErrorMessage("请选择要关联一次设备的数据！");
		}
	}

	private void initProKind() {
		proKinds.add("主一保护");
		proKinds.add("主二保护");
		proKinds.add("主三保护");
		proKinds.add("断路器保护");
		proKinds.add("辅A保护");
		proKinds.add("辅B保护");
		proKinds.add("非电量保护");
		proKinds.add("短引线保护");
	}

	/**
	 * 变电站
	 * @param query
	 * @return
	 */
	public List<String> completeStationNames(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : cimstation.keySet()) {
			if (s.startsWith(query))
				results.addAll(cimstation.get(s));
		}
		return results;
	}

	/**
	 * 一次设备名称
	 * @param query
	 * @return
	 */
	public List<String> completeEquipmentNames(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : primEquipments.keySet()) {
			if (s.startsWith(query))
				results.addAll(primEquipments.get(s));
		}
		return results;
	}

	/**
	 * 生产厂家
	 * @param query
	 * @return
	 */
	public List<String> completeDevManufacturer(String query) {
		List<String> results = new ArrayList<String>();
		for (String s : devManufacturerMap.keySet()) {
			if (s.startsWith(query))
				results.addAll(devManufacturerMap.get(s));
		}
		return results;
	}

	/**
	 * 保存设备关联
	 */
	public void update() {

		if (selected != null) {

			ProtectionEquipment pre = new ProtectionEquipment();
			try {
				BeanUtils.copyProperties(pre, selected);
				String selectStation = null;
				if (StringUtils.isNotEmpty(station)) {
					for (Substation s : cc.getStationid_map().values()) {
						if (s.getName().equals(station)) {
							selectStation = s.getId();
							break;
						}
					}
				}
				int oldIndex = currentDeviceProList.indexOf(selected);// 找到原位置
				pre.setSubId(selectStation);
				pre.setSubName(station);
				pre.setProtectedId(deviceId);
				pre.setProtectedName(deviceName);
				BeanUtils.copyProperties(selected, pre);
				currentDeviceProList.set(oldIndex, selected);// 替换
			} catch (IllegalAccessException | InvocationTargetException e) {
				e.printStackTrace();
			}
			dao.update(pre, ProtectionEquipment.class);
			addSuccessMessage("绑定成功");
		}
	}

	public List<ProtectionEquipmentDTO> getSelects() {
		return selects;
	}

	public void setSelects(List<ProtectionEquipmentDTO> selects) {
		this.selects = selects;
	}

	public String getStation() {
		return station;
	}

	public void setStation(String station) {
		this.station = station;
	}

	public String getDeviceName() {
		return deviceName;
	}

	public void setDeviceName(String deviceName) {
		this.deviceName = deviceName;
	}

	public ProtectionEquipmentDTO getSelected() {
		return selected;
	}

	public void setSelected(ProtectionEquipmentDTO selected) {
		this.selected = selected;
	}

	public List<String> getProKinds() {
		return proKinds;
	}

	public void setProKinds(List<String> proKinds) {
		this.proKinds = proKinds;
	}

	public List<String> getProtectedTypes() {
		return protectedTypes;
	}

	public void setProtectedTypes(List<String> protectedTypes) {
		this.protectedTypes = protectedTypes;
	}
}
